package handler

import (
    "gougouapi/core"
    "gougouapi/result"
    "gougouapi/core/err"
    "fmt"
    "gougouapi/variables"
    "sort"
    "strings"
    "crypto/md5"
)

type Base struct {
    core.HttpHandler
}

func (this *Base) PreAction() error {
    this.Request.ParseForm()
    if err := this.signature(); err != nil {
        return err
    }
    return nil
}

func (this *Base) DealErr(e error, reply *core.HttpReply) {
    res := &result.Model{}
    if ee, ok := e.(*err.Err); ok {
        reply.HeaderCode = ee.HeaderCode
        res.Code = ee.Code
        res.Message = ee.Message
    } else {
        res.Message = e.Error()
        res.Code = err.ServerErr
        reply.HeaderCode = 503
    }
    reply.Data = res
}

func (this *Base) signature() error {
    timeStamp := this.Request.Header.Get("Time-Stamp")
    signKey := this.Request.Header.Get("Sign-Key")
    if timeStamp == "" {
        return err.NewErr(err.HeaderErr, "Head loss Time-Stamp")
    }
    if signKey == "" {
        return err.NewErr(err.HeaderErr, "Head loss Sign-Key")
    }
    keys := []string{}
    for k, _ := range this.Request.Form {
        keys = append(keys, k)
    }
    sort.Strings(keys)
    tmpAry := []string{}
    for _, key := range keys {
        s := strings.Join(this.Request.Form[key], "|")
        tmpAry = append(tmpAry, key + "=" + s)
    }
    str := strings.Join(tmpAry, "&") + timeStamp + variables.AppConfig.Secret
    key := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(str))))
    fmt.Println(str)
    fmt.Println(key)
    if key != signKey {
        info := " str:" + str + " key:" + key
        e := err.NewErr(err.ServerErr, "Signature error" + info)
        return e
    }

    return nil
}

